<?php
// portfolio custom post type			
$labels = array(
    'name'                  => _x('Portfolio', 'post type general name', 'dt'),
    'singular_name'         => _x('Portfolio', 'post type singular name', 'dt'),
    'add_new'               => _x('Add New', 'dt', 'dt'),
    'add_new_item'          => __('Add New Item', 'dt'),
    'edit_item'             => __('Edit Item', 'dt'),
    'new_item'              => __('New Item', 'dt'),
    'view_item'             => __('View Item', 'dt'),
    'search_items'          => __('Search Items', 'dt'),
    'not_found'             =>  __('No items found', 'dt'),
    'not_found_in_trash'    => __('No items found in Trash', 'dt'), 
    'parent_item_colon'     => '',
    'menu_name'             => 'Portfolio'
);

$img = get_template_directory_uri(). '/images/admin_ico_portfolio.png';

$args = array(
    'labels'                => $labels,
    'public'                => true,
    'publicly_queryable'    => true,
    'show_ui'               => true,
    'show_in_menu'          => true, 
    'query_var'             => true,
    'rewrite'               => true,
    'capability_type'       => 'post',
    'has_archive'           => true, 
    'hierarchical'          => false,
    'menu_position'         => 27,
    'menu_icon'             => $img,
    'supports'              => array( 'title', 'editor', 'thumbnail', 'comments', 'excerpt' )
);

register_post_type( 'dt_portfolio', $args );
			
/* TAXONOMY for portfolio */			
$labels = array(
    'name'              => _x( 'Categories', 'taxonomy general name', LANGUAGE_ZONE ),
    'singular_name'     => _x( 'Category', 'taxonomy singular name', LANGUAGE_ZONE ),
    'search_items'      => __( 'Search in Category', 'dt' ),
    'all_items'         => __( 'Categories', 'dt' ),
    'parent_item'       => __( 'Parent Category', 'dt' ),
    'parent_item_colon' => __( 'Parent Category:', 'dt' ),
    'edit_item'         => __( 'Edit Category', 'dt' ), 
    'update_item'       => __( 'Update Category', 'dt' ),
    'add_new_item'      => __( 'Add New Category', 'dt' ),
    'new_item_name'     => __( 'New Category Name', 'dt' ),
    'menu_name'         => __( 'Categories', 'dt' ),
); 	

register_taxonomy(
    'dt_portfolio_category',
    array( 'dt_portfolio' ),
    array(
        'hierarchical'          => true,
        'show_in_nav_menus '    => false,
        'public'                => false,
        'show_tagcloud'         => false,
        'labels'                => $labels,
        'show_ui'               => true,
        'rewrite'               => true
    )
);
			

// WP 3.0+
add_action( 'add_meta_boxes', 'dt_portfolio_box' );

/* Do something with the data entered */
add_action( 'save_post', 'dt_portfolio_list_save' );
add_action( 'save_post', 'dt_portfolio_hide_meta_save' );

function dt_portfolio_box() {
    
    add_meta_box(
        'portfolio-hide_meta',
        __( 'Portfolio options', LANGUAGE_ZONE ),
        'dt_portfolio_hide_meta_inner_box',
        'dt_portfolio',
        'side'
    );
    
    // portfolio list meta box for layout
    if ( isset($_GET['post']) ) {
        $post_id = $_GET['post'];
    } elseif ( isset($_POST['post_ID']) ) {
        $post_id = $_POST['post_ID'];
    } else
        return;
    
    $template_file = get_post_meta($post_id,'_wp_page_template',TRUE);

    // check for a template type
    if( 'dt_portfolio.php' == $template_file || 'dt_portfolio_index.php' == $template_file ) {
        add_meta_box(
            'portfolio-list',
            __( 'Portfolio options', LANGUAGE_ZONE ),
            'dt_portfolio_list_inner_box',
            'page'
        );
    }
}
			
// portfolio layout metabox
function dt_portfolio_list_inner_box( $post ){
    $box_name = 'dt_portfolio_layout';
    
    $terms = get_categories(
        array(
            'type'                     => 'dt_portfolio',
            'hide_empty'               => 1,
            'hierarchical'             => 0,
            'taxonomy'                 => 'dt_portfolio_category',
            'pad_counts'               => false
        )
    );
    
    $defaults = array(
        'list'          => array(),
        'ppp'           => '',
        'orderby'       => 'date',
        'order'         => 'DESC',
        'slug'          => 'portf_cat'
    );
    $options = get_post_meta( $post->ID, $box_name, true );
    $options = wp_parse_args( $options, $defaults );
    
    // Use nonce for verification
    wp_nonce_field( plugin_basename( __FILE__ ), $box_name. '_nonce' );
    
    ?>
    
    <?php
    // print select list
    dt_admin_select_list(
        array(
            'rad_butt_name' => 'show_type_portf',
            'checkbox_name' => 'show_portf',
            'terms'         => &$terms,
            'current_sel'   => $options['list'],
            'con_class'     => 'portfolio-list'
        )    
    );
    ?>
    
    <hr/>
    
    <?php
    // posts_per_page
    dt_admin_ppp_options(
        array(
            'options'   => $options,
            'box_name'  => $box_name
        )
    );
    ?>

    <hr/>
    
    <?php
    // print order options
    dt_admin_order_options(
        array(
            'options'   => $options,
            'box_name'  => $box_name
        )
    );
    ?>
    
    <?php
}
			
// portfolio layout metabox save
function dt_portfolio_list_save( $post_id ) {
    $box_name = 'dt_portfolio_layout';
    
    // verify if this is an auto save routine. 
    // If it is our form has not been submitted, so we dont want to do anything
  
    if ( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE ) 
        return;

    // verify this came from the our screen and with proper authorization,
    // because save_post can be triggered at other times

    if ( !isset( $_POST[$box_name. '_nonce'] ) || !wp_verify_nonce( $_POST[$box_name. '_nonce'], plugin_basename( __FILE__ ) ) )
        return;

    // Check permissions
    if ( !current_user_can( 'edit_page', $post_id ) )
        return;
                    
    $mydata = null;
    switch( $_POST['show_type_portf'] ) {
        case 'only':
            if( isset($_POST['show_portf']['only']) ) {
                $mydata['list']['only'] = $_POST['show_portf']['only'];
            }
            break;
        case 'except':
            if( isset($_POST['show_portf']['except']) ) {
                $mydata['list']['except'] = $_POST['show_portf']['except'];
            }
            break;
        default:
            $mydata['list'] = null;
    }
    
    if( !empty($_POST[$box_name. '_ppp']) ) {
        $mydata['ppp'] = intval($_POST[$box_name. '_ppp']);
    }
    
    if( isset($_POST[$box_name. '_orderby']) ) {
        $mydata['orderby'] = $_POST[$box_name. '_orderby'];
    }
    
    if( isset($_POST[$box_name. '_order']) ) {
        $mydata['order'] = $_POST[$box_name. '_order'];
    }
    
    update_post_meta( $post_id, $box_name, $mydata );
}

// portfolio hide meta in details
function dt_portfolio_hide_meta_inner_box( $post ){
    $box_name = 'dt_portfolio_hide_meta';
    
    $defaults = array(
        'hide_meta'          => false
    );
    $options = get_post_meta( $post->ID, $box_name, true );
    $options = wp_parse_args( $options, $defaults );
    
    // Use nonce for verification
    wp_nonce_field( plugin_basename( __FILE__ ), $box_name. '_nonce' );
    
    ?>
    
    <input type="checkbox" id="<?php esc_attr_e($box_name); ?>_hide_meta" name="<?php esc_attr_e($box_name); ?>_hide_meta" <?php checked( $options['hide_meta'], true ); ?>/>
    <label for="<?php esc_attr_e($box_name); ?>_hide_meta"><?php _e( 'Hide meta data in post details', LANGUAGE_ZONE ); ?></label>
    
    <?php
}

function dt_portfolio_hide_meta_save( $post_id ) {
    $box_name = 'dt_portfolio_hide_meta';
    
    // verify if this is an auto save routine. 
    // If it is our form has not been submitted, so we dont want to do anything
  
    if ( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE ) 
        return;

    // verify this came from the our screen and with proper authorization,
    // because save_post can be triggered at other times

    if ( !isset( $_POST[$box_name. '_nonce'] ) || !wp_verify_nonce( $_POST[$box_name. '_nonce'], plugin_basename( __FILE__ ) ) )
        return;

    // Check permissions
    if ( !current_user_can( 'edit_page', $post_id ) )
        return;
                    
    $mydata = null;
    
    $mydata['hide_meta'] = isset($_POST[$box_name . '_hide_meta']);
    
    update_post_meta( $post_id, $box_name, $mydata );
}
			
// add portfolio to autor archive
function __set_portfolio_for_author( &$query )
{
    if ( $query->is_author )
        $query->set( 'post_type', array( 'portfolio', 'post') );
    remove_action( 'pre_get_posts', '__set_portfolio_for_author' ); // run once!
}
//add_action( 'pre_get_posts', '__set_portfolio_for_author' );

// taxonomy list
function dt_portf_tax_list( array $options ) {
    global $post;
    static $portf_slug = 'portfolio_category';
    $portf_type = 'dt_portfolio';
    $portf_tax = 'dt_portfolio_category';
    $before_title = '<span>';
    $after_title = '</span>';
    
    if( !empty($options['portf_slug']) ) {
        $portf_slug = $options['portf_slug'];
    }
    
    if( !empty($options['post_type']) ) {
        $portf_type = $options['post_type'];
    }
    
    if( !empty($options['post_taxonomy']) ) {
        $portf_tax = $options['post_taxonomy'];
    }
    
    // for other button
    $tax = get_terms( $portf_tax, array('fields' => 'ids') );
    $query = new Wp_Query(
        array(	
            'post_type'		=> $portf_type,
            'tax_query'		=> array(
                array(
                    'taxonomy'	=> $portf_tax,
                    'field'		=> 'id',
                    'terms'		=> $tax,
                    'operator'	=> 'NOT IN'
                )
            ),
            'posts_per_page'	=> 1
        )
    );
    $others_flag = $query->found_posts?true:false;
    // end other part
    
    $term_args = array(
        'type'          => $portf_type,
        'hide_empty'    => 1,
        'hierarchical'  => 0,
        'taxonomy'      => $portf_tax,
        'pad_counts'    => false
    );
    
    $default = array(
        'a_class'		=> 'filter',
        'c_class'		=> 'filters',
        'ajax'			=> false,
        'tax'			=> null
    );
    
    $o = wp_parse_args( $options, $default );
    
    $tax_key = $o['tax']?key( $o['tax'] ):$o['tax'];
    $cur_cat = $out = $href = $href_plus = '';
                    
    // set glue element for href
    $href = get_permalink();
    
    if( isset($_GET[$portf_slug]) ){
        $cur_cat = trim( (string) $_GET[$portf_slug] );
    }
    
    $href_plus = add_query_arg(
        array(
            $portf_slug => ''
        ),
        $href
    );
    $href_plus .= '=';
    
    $href_other = add_query_arg(
        array(
            $portf_slug => 'none'
        ),
        $href
    );
    
    $anchor = '';
    
    if( $o['ajax'] ) {
        $href = '#all/1';
        $href_other = '#none/1';
        $href_plus = '#';
        $anchor = '/1';
    }

    if( 'except' == $tax_key ) {
        $term_args['exclude'] = current( $o['tax'] );
    }elseif( 'only' == $tax_key ) {
        $term_args['include'] = current( $o['tax'] );
    }

    $terms = get_categories( $term_args );
    if( 1 == count($terms) )
        return '';

    if( $terms ){
        $out .= '<div class="'. esc_attr($o['c_class']). '">';
        $out .= '<a href="'. esc_url( $href ). '"'. ($cur_cat?'':' class="act"'). '>';
        $out .= $before_title. __( 'View all', LANGUAGE_ZONE ). $after_title;
        $out .= '</a>';
        foreach( $terms as $term ){
            $act = '';
                        
            if( $cur_cat == $term->slug && !$o['ajax'] ) {
                $act = ' class="act"';
            }
            
            $out .= '<a href="'. esc_url( $href_plus. $term->slug . $anchor ). '"'. $act. '>';
            $out .= $before_title. $term->name. $after_title;
            $out .= '</a>';
        }
        
        if ( $others_flag ) {
            $out .= '<a href="'. esc_url( $href_other ). '"'. ('none' == $cur_cat?' class="act"':''). '>';
            $out .= $before_title. __( 'Other', LANGUAGE_ZONE ). $after_title;
            $out .= '</a>';
        }
        $out .= '</div>';
    }
    return $out;
}